package org.scohen.juploadr.app;

import java.io.File;
import java.util.Comparator;
import java.util.Date;

import au.com.lastweekend.jim.io.exif.ExifDirectory;
import au.com.lastweekend.jim.io.jpeg.JpegReader;
import au.com.lastweekend.jim.io.metadata.Directory;
import au.com.lastweekend.jim.io.metadata.Metadata;

/**
 * This comparator compares two UploadImages by their EXIF created dates. if the
 * created dates don't exits, it falls back on the actual file's last modified
 * date.
 * 
 * @author steve
 * 
 */
public class ImageAttributesEXIFCreateDateComparator implements Comparator<UploadImage> {

    public int compare(UploadImage i1, UploadImage i2) {
        Date d1;
        Date d2;
        try {
            JpegReader reader = new JpegReader();
            Metadata md1 = reader.readMetadata(new File(i1.getImagePath()));
            Metadata md2 = reader.readMetadata(new File(i2.getImagePath()));
            Directory dir1 = md1.getDirectory(ExifDirectory.class);
            Directory dir2 = md2.getDirectory(ExifDirectory.class);

            d1 = dir1.getDate(ExifDirectory.TAG_DATETIME_ORIGINAL);
            d2 = dir2.getDate(ExifDirectory.TAG_DATETIME_ORIGINAL);
        } catch (Exception e) {
            // eek... no exif data?
            File f1 = new File(i1.getImagePath());
            File f2 = new File(i2.getImagePath());
            d1 = new Date(f1.lastModified());
            d2 = new Date(f2.lastModified());
        }
        int cmp = d2.compareTo(d1);
        if (cmp == 0) {
            String filename1 = i1.getImagePath().substring(i1.getImagePath().lastIndexOf(File.separator));
            String filename2 = i2.getImagePath().substring(i2.getImagePath().lastIndexOf(File.separator));
            cmp = filename2.compareTo(filename1);
        }
        return cmp;
    }
}
